package com.github_dididipapa.mall.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github_dididipapa.common.utils.PageUtils;
import com.github_dididipapa.common.utils.Query;
import com.github_dididipapa.mall.product.dao.ProductAttrValueDao;
import com.github_dididipapa.mall.product.entity.ProductAttrValueEntity;
import com.github_dididipapa.mall.product.service.ProductAttrValueService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@RequiredArgsConstructor
@Service("productAttrValueService")
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueDao, ProductAttrValueEntity> implements ProductAttrValueService {
    @Lazy
    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<ProductAttrValueEntity> page = this.page(
                new Query<ProductAttrValueEntity>().getPage(params),
                new QueryWrapper<ProductAttrValueEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * @description: 批量更新规格参数
     * 老实讲有点怪怪的，但不这么写的话就是N+1的更新操作
     * @author: dididi_papa
     * @date: 2025/6/29 下午4:24
     * @param: [spuId, entities]
     * @return: void
     **/
    @Transactional
    @Override
    public void updateBatchBySpuId(Long spuId, List<ProductAttrValueEntity> entities) {
//        //1、删除
//        if(spuId != null && spuId > 0 ) {
//            productAttrValueService.getBaseMapper().delete(
//                    new QueryWrapper<ProductAttrValueEntity>()
//                            .eq("spu_id", spuId));
//        }
//        //2、添加新的记录
//        for (ProductAttrValueEntity entity : entities){
//            entity.setSpuId(spuId);
//        }
//        productAttrValueService.saveBatch(entities);

        //N + 1写法数据库好看一点：）
        for (ProductAttrValueEntity entity : entities) {
            productAttrValueService.update(entity,
                    new UpdateWrapper<ProductAttrValueEntity>()
                            .eq("spu_id",spuId)
                            .eq("attr_id", entity.getAttrId()));
        }
    }

    @Override
    public List<ProductAttrValueEntity> baseAttrListForSpu(Long spuId) {
        return productAttrValueService.list(
                        new QueryWrapper<ProductAttrValueEntity>()
                        .eq("spu_id", spuId));
    }

}